<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>权限列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!--        卡片视图-->
        <el-card>
            <el-row>
                <el-col>
                    <el-button type="primary" @click="roleAdduser">添加角色</el-button>
                </el-col>
            </el-row>

            <!--            用户表格区域-->
            <el-table :data="roleList" stripe border style="width: 100%">
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-row v-for="(item,i1) in scope.row.children"
                                :class="['DBbottom',i1 ===0 ? 'DBtop':'','vcenter']" :key="item.id">
                            <!--  一级权限的渲染-->
                            <el-col :span="5">
                                <el-tag closable @close="removeRightById(scope.row, item.id)"
                                >{{item.authName}}
                                </el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!--  二级权限的渲染-->
                            <el-col :span="19">
                                <!-- 通过for循环嵌套渲染二级权限 -->
                                <el-row v-for="(item2 ,i2) in item.children" :key="item2.id">
                                    <el-col :span="6">
                                        <el-tag type="success" :class="[i2 === 0? '':'DBtop','vcenter']"
                                                closable @close="removeRightById(scope.row, item2.id)">
                                            {{item2.authName}}
                                        </el-tag>
                                    </el-col>
                                    <el-col :span="18">
                                        <el-tag type="warning" closable v-for="(item3) in item2.children"
                                                :key="item3.id"
                                                @close="removeRightById(scope.row, item3.id)">{{item3.authName}}
                                        </el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
                <el-table-column type="index"></el-table-column>
                <el-table-column prop="roleName" label="角色名称"></el-table-column>
                <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="editRole(scope.row.id)">编辑
                        </el-button>
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="RoleDelete(scope.row.id)">
                            删除
                        </el-button>
                        <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRoleRight(scope.row)">
                            分配权限
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!--  添加用户弹框  -->
            <el-dialog
                    :visible.sync="PowerAddDialogVisible"
                    title="添加用户"
                    width="50%"
                    @close="addClose">
            <span class="dialog-footer" slot="footer">
                <el-form :model="roleForm" :rules="roleListRules" label-width="80px" ref="roleForm">
         <el-form-item label="角色名称" prop="roleName">
             <el-input v-model="roleForm.roleName"></el-input>
           </el-form-item>
                    <el-form-item label="角色描述" prop="roleDesc">
             <el-input v-model="roleForm.roleDesc"></el-input>
           </el-form-item>
                </el-form>
                <el-button @click="PowerAddDialogVisible = false">取 消</el-button>
                <el-button @click="roleReady" type="primary">确 定</el-button>
            </span>
            </el-dialog>
            <!--            修改角色-->
            <el-dialog
                    :visible.sync="PowerEditDialogVisible"
                    title="添加用户"
                    width="50%"
                    @close="editClose">
            <span class="dialog-footer" slot="footer">
                <el-form :model="roleForm" :rules="roleListRules" label-width="80px" ref="editForm">
         <el-form-item label="角色名称" prop="roleName">
             <el-input v-model="roleForm.roleName"></el-input>
           </el-form-item>
                    <el-form-item label="角色描述" prop="roleDesc">
             <el-input v-model="roleForm.roleDesc"></el-input>
           </el-form-item>
                </el-form>
                <el-button @click="PowerEditDialogVisible = false">取 消</el-button>
                <el-button @click="roleEditReady" type="primary">确 定</el-button>
            </span>
            </el-dialog>
            <!--            分配权限的弹框-->
            <el-dialog
                    :visible.sync="SetroleRightDialogVisible"
                    title="添加用户"
                    width="50%"
            @close="setRightClose">
                <el-tree :data="rightsList" :props="treeProps" ref="treeRef"
                         default-expand-all show-checkbox node-key="id" :default-checked-keys="defArray"></el-tree>
                <span class="dialog-footer" slot="footer">
                <el-button @click="SetroleRightDialogVisible = false">取 消</el-button>
                <el-button @click="allotRights" type="primary">确 定</el-button>
            </span>
            </el-dialog>
        </el-card>
    </div>
</template>

<script>
  export default {
    name: "roles",
    data() {
      return {
        //所有角色列表数据
        roleList: [],
        rightsList: [],//保存所有权限的数据
        treeProps: {
          children: 'children',
          label: 'authName',
        },
        defArray: [],//默认被勾选的id节点数组
        PowerAddDialogVisible: false,
        PowerEditDialogVisible: false,
        SetroleRightDialogVisible: false,
        roleListRules: {
          roleName: [{required: true, message: '请输入角色名称', trigger: 'blur'}],
          roleDesc: [{required: true, message: '请输入角色描述', trigger: 'blur'}]
        },
        roleForm: {
          roleName: '',
          roleDesc: '',
        },
        roleId:'',
      }
    },
    created() {
      this.getRolesList()
    },
    methods: {
      //获取所有角色列表数据
      async getRolesList() {
        const {data: res} = await this.$http.get('roles')
        if (res.meta.status !== 200) return this.$message.error('获取用户列表失败')
        this.roleList = res.data
        console.log(this.roleList);
      },
      addClose() {
        this.$refs.roleForm.resetFields()
      },
      editClose() {
        this.$refs.editForm.resetFields()
      },
      //点击添加用户按钮
      roleAdduser() {
        this.PowerAddDialogVisible = true
      },

      //添加弹框确认点击
      roleReady() {
        this.$refs.roleForm.validate(async valid => {
          if (!valid) return
          //成功  发起添加用户的请求
          const {data: res} = await this.$http.post('roles', this.roleForm)
          if (res.meta.status !== 201) return this.$message.error('添加用户失败')
          this.$message.success('添加用户成功')
          this.PowerAddDialogVisible = false
          this.getRolesList()//重新获取角色列表

        })
      },
      setRightClose(){
        this.defArray = []
      },
      //根据id进行查询点击哪行编辑
      async editRole(id) {
        const {data: res} = await this.$http.get('roles/' + id)
        if (res.meta.status !== 200) return
        //查询成功
        this.roleForm = res.data
        this.PowerEditDialogVisible = true
      },
      //角色修改的点击确认
      async roleEditReady() {
        //发送修改用户角色请求
        const {data: res} = await this.$http.put('roles/' + this.roleForm.roleId, this.roleForm)
        if (res.meta.status !== 200) return
        this.$message.success('修改用户角色成功')
        this.getRolesList()
        this.PowerEditDialogVisible = false
      },
      //角色删除
      async RoleDelete(id) {
        const {data: res} = await this.$http.delete('roles/' + id)
        if (res.meta.status !== 200) return
        this.$message.success('用户角色删除成功')
        this.getRolesList()
      },
      //三级权限的删除
      async removeRightById(role, rightId) {
        const configresult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        //如果为点击确定 返回configresult为confirm字符串   取消则返回cancel字符串
        if (configresult !== 'confirm') {
          return this.$message.info('已经取消了删除')
        } else {
          //发起删除该行用户信息
          const {data: res} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
          if (res.meta.status !== 200) return this.$message.error('删除失败')
          this.$message.success('删除用户成功')
          //删除成功 重新查询信息
          role.children = res.data
        }
      },
      //分配权限按钮的点击
      async setRoleRight(role) {
        this.roleId = role.id
        //获取所有权限的数据
        const {data: res} = await this.$http.get('rights/tree')
        if (res.meta.status !== 200) return
        this.rightsList = res.data //将请求到的权限数据保存起来
        this.getdefArray(role,this.defArray)//递归获取所有角色的三级权限
        this.SetroleRightDialogVisible = true
        console.log(this.rightsList)

      },

      //通过递归的形式 获取所有角色三级权限下所有属性id，并保存到被勾选数组defArray中
      getdefArray(node, arr) {
        //判断是否有children属性  没有就是三级节点
        if (!node.children) {
          //是三级节点 接收它的id值
          return arr.push(node.id)
        } else {
          node.children.forEach(item => {
            this.getdefArray(item, arr)
          })
        }
      },
      //点击为角色分配权限
     async allotRights(){
        const keys = [
          ...this.$refs.treeRef.getCheckedKeys(),
          ...this.$refs.treeRef.getHalfCheckedKeys()
        ]
        console.log(keys)
        const idstr = keys.join(',')
        const {data :res} = await this.$http.post(`roles/${this.roleId}/rights` ,{rids : idstr})
         if (res.meta.status !==200 ) return this.$message.error('分配权限失败')
       this.$message.success('分配权限成功')
       this.SetroleRightDialogVisible = false
       this.getRolesList()
      }
    }
  }
</script>

<style scoped>
    .el-tag {
        margin: 10px;
    }

    .DBbottom {
        border-bottom: 1px solid #eee;
    }

    .DBtop {
        border-top: 1px solid #eee;
    }

    .vcenter{
       display: flex;
        align-items: center;
    }
</style>